<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { Edit, Search, Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'
import type { TabsPaneContext } from 'element-plus'
import type { UploadProps } from 'element-plus'
import dayjs from 'dayjs'
import {
  type SearchAssetConsDto,
  type AmsAssetConsLog,
  type AssetConsLogsDto,
  type AssetDto,
  type AssetConsListDto,
} from '@/api/ams'
import {
  getAssetConsPage,
  getAssetConsList,
  getAssetConsLogsPage,
  assetConsLogsAdd,
  getuploadOrderPicUri,
  callOCR,
  getAxiosBaseURL,
} from '@/api/ams'

defineOptions({
  name:"AssetConsumables"
})

const searchDto = reactive<SearchAssetConsDto>({
  assetId: '',
  operationType: '',
  applicant: '',
  pageNum: 1,
  pageSize: 10,
})

const tableData1 = ref<AssetDto[]>([])
const pagination1 = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1,
})
const tableData2 = ref<AssetConsLogsDto[]>([])
const pagination2 = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1,
})
const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
const headers = {
  authorization: getToken(),
}
const consList = ref<AssetConsListDto[]>([])
onMounted(() => {
  getAssetConsList().then((res) => {
    consList.value = res
  })
  clickSearchBtn()
})

const clickSearchBtn = () => {
  getAssetConsLogsPage(searchDto).then((res) => {
    tableData2.value = res.list
    pagination2.total = res.total
  })
  getAssetConsPage({
    assetCode: '',
    labelCode: '',
    name: '',
    pageNum: pagination1.currentPage,
    pageSize: pagination1.pageSize,
  }).then((res) => {
    tableData1.value = res.list
    pagination1.total = res.total
  })
}
const isAddDialog = ref(true) //
const showDialog = ref(false) // 是否显示模态框
const dialogForm = reactive<AmsAssetConsLog>({})
const currFormName = ref('')
const imageUrl = ref('')

const clickInBtn = (row: AssetDto) => {
  isAddDialog.value = true
  showDialog.value = true
  dialogForm.assetId = row.id
  currFormName.value = row.name
  imageUrl.value = ''
}
const clickOutBtn = (row: AssetDto) => {
  isAddDialog.value = false
  showDialog.value = true
  dialogForm.assetId = row.id
  currFormName.value = row.name
  imageUrl.value = ''
}
const clickOCRBtn = () => {
  callOCR()
}
const clickSubDialogForm = () => {
  if (isAddDialog.value) {
    dialogForm.operationType = 'in'
  } else {
    dialogForm.operationType = 'out'
  }
  assetConsLogsAdd(dialogForm).then(() => {
    clickSearchBtn()
    showDialog.value = false
  })
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  console.log(response, uploadFile)
  dialogForm.picture = response.filename
  imageUrl.value = getAxiosBaseURL() + '/ams/static/orderPic/' + response.filename
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile.type)
  if (!rawFile.type.startsWith('image')) {
    ElMessage.error('OCR只能解析传统image类型文件')
    return false
  }
  return true
}
</script>

<template>
  <div>
    <el-dialog v-model="showDialog" :title="isAddDialog ? '消耗品入库' : '消耗品出库'" width="500">
      <el-form :model="dialogForm" label-width="auto" style="max-width: 600px">
        <el-form-item label="耗材名称">
          <el-input v-model="currFormName" />
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="dialogForm.num" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="dialogForm.unit" />
        </el-form-item>
        <el-form-item label="领用人">
          <el-input v-model="dialogForm.applicant" />
        </el-form-item>
        <el-form-item label="经办人">
          <el-input v-model="dialogForm.operator" />
        </el-form-item>
        <el-form-item label="管理员">
          <el-input v-model="dialogForm.admin" />
        </el-form-item>
        <el-form-item label="单据编号">
          <el-input v-model="dialogForm.orderCode" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="dialogForm.notes" />
        </el-form-item>
        <el-form-item label="" class="up-file-item">
          <el-upload
            class="avatar-uploader"
            :headers="headers"
            name="file"
            :action="getuploadOrderPicUri()"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            ><img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="clickOCRBtn"> OCR解析 </el-button>
          <el-button type="primary" @click="clickSubDialogForm"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-row>
      <el-col>
        <el-card>
          <el-row class="mb-5">
            <el-col>
              <el-select
                v-model="searchDto.assetId"
                filterable
                placeholder="按资产名称过滤"
                class="mr-2"
                style="width: 240px"
                clearable
              >
                <el-option
                  v-for="item in consList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                v-model="searchDto.operationType"
                placeholder="全部"
                style="width: 240px"
                class="mr-2"
              >
                <el-option label="全部" value="" />
                <el-option label="入库记录" value="in" />
                <el-option label="领用记录" value="out" />
              </el-select>
              <el-input
                style="width: 240px"
                v-model="searchDto.applicant"
                class="max-w-xs mr-5 width"
                placeholder="请输入领用人"
                clearable
              />
              <el-button type="primary" :icon="Search" @click="clickSearchBtn">查询</el-button>
            </el-col>
          </el-row>
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="库存清单" name="first">
              <el-table :data="tableData1" stripe style="width: 100%" show-overflow-tooltip>
                <el-table-column type="index" width="50" label="#" />
                <el-table-column prop="assetCode" label="资产编号" width="100" />
                <el-table-column prop="labelType" label="标签类型" />
                <el-table-column prop="labelCode" label="标签编码" />
                <el-table-column prop="typeName" label="资产类型">
                  <template #default="scope">
                    <el-tag :type="scope.row.typeId == 1 ? 'primary' : 'info'">{{
                      scope.row.typeName
                    }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="categoryName" label="资产分类" />
                <el-table-column prop="name" label="名称" />
                <el-table-column prop="description" label="描述" />
                <el-table-column prop="tag" label="标签"> </el-table-column>
                <el-table-column prop="num" label="数量" />
                <el-table-column fixed="right" label="操作" width="180">
                  <template #default="scope">
                    <el-link :icon="Edit" type="primary" class="mr-3" @click="clickInBtn(scope.row)"
                      >入库</el-link
                    >
                    <el-link
                      :icon="Delete"
                      type="primary"
                      class="mr-3"
                      @click="clickOutBtn(scope.row)"
                      >出库</el-link
                    >
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                class="mt-5"
                layout="prev, pager, next"
                :hide-on-single-page="pagination1.total / pagination1.pageSize < 2"
                :total="pagination1.total"
              />
            </el-tab-pane>
            <el-tab-pane label="领用记录" name="second">
              <el-table :data="tableData2" style="width: 100%" show-overflow-tooltip>
                <el-table-column type="index" width="50" label="#" />
                <el-table-column prop="assetName" label="名称" width="100" />
                <el-table-column prop="assetDesc" label="描述" />
                <el-table-column prop="operationType" label="记录类型">
                  <template #default="scope">
                    <el-tag :type="scope.row.operationType == 'in' ? 'primary' : 'success'">{{
                      scope.row.operationType == 'in' ? '入库' : '出库'
                    }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="num" label="数量" width="50" />
                <el-table-column prop="unit" label="单位" width="50" />
                <el-table-column prop="applicant" label="领用人" width="70" />
                <el-table-column prop="operator" label="经办人" width="70" />
                <el-table-column prop="admin" label="管理员" width="70" />
                <el-table-column prop="orderCode" label="单据编号" />
                <el-table-column prop="notes" label="备注信息" />
                <el-table-column prop="createAt" label="时间" width="150">
                  <template #default="scope">
                    {{ dayjs(new Date(scope.row.createAt * 1000)).format('YYYY-MM-DD HH:mm:ss') }}
                  </template>
                </el-table-column>
                <el-table-column prop="num" label="单据预览">
                  <template #default="scope">
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="getAxiosBaseURL() + '/ams/static/orderPic/' + scope.row.picture"
                      :zoom-rate="1.2"
                      :max-scale="7"
                      :min-scale="0.2"
                      preview-teleported
                      :preview-src-list="[
                        getAxiosBaseURL() + '/ams/static/orderPic/' + scope.row.picture,
                      ]"
                      show-progress
                      :initial-index="0"
                      fit="cover"
                    />
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                class="mt-5"
                layout="prev, pager, next"
                :hide-on-single-page="pagination2.total / pagination2.pageSize < 2"
                :total="pagination2.total"
              />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
:deep(.up-file-item .el-form-item__content) {
  display: flex;
  justify-content: center;
}

:deep(.avatar) {
  width: 80px;
  height: 80px;
}
:deep(.avatar-uploader .el-upload) {
  width: 100%;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}
:deep(.el-icon.avatar-uploader-icon) {
  font-size: 80px;
  color: #8c939d;
  text-align: center;
}
</style>
